// pages/Plan/PlanCard.jsx
import { CreateCustomerPortalSession, Subscribe } from "api/mutations";
import Loader from "components/atoms/Loader";
import { ENABLE_CUSTOMER_PORTAL } from "config";
import ConfirmAlert from "libs/confirmAlert";
import { formatMoney } from "libs/utils";
import { useState } from "react";
import { useTranslation } from "react-i18next";
import { useMutation, useQueryClient } from "react-query";
import { useStripe } from '@stripe/react-stripe-js';
import {
  Card,
  CardHeader,
  CardContent,
  Typography,
  Button,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  List,
  ListItem,
  ListItemIcon,
  ListItemText
} from '@mui/material';
import CheckIcon from '@mui/icons-material/Check';
import { styled } from '@mui/material/styles';

// Styled components with cyberpunk aesthetic
const CyberCard = styled(Card)(({ theme }) => ({
  background: theme.palette.mode === 'dark'
    ? 'linear-gradient(145deg, rgba(20, 20, 30, 0.8), rgba(10, 10, 15, 0.9))'
    : 'linear-gradient(145deg, rgba(255, 255, 255, 0.9), rgba(240, 240, 250, 0.8))',
  borderRadius: '16px',
  padding: theme.spacing(1),
  height: '100%',
  position: 'relative',
  overflow: 'hidden',
  border: theme.palette.mode === 'dark'
    ? '1px solid rgba(0, 255, 242, 0.2)'
    : '1px solid rgba(0, 180, 170, 0.2)',
  boxShadow: theme.palette.mode === 'dark'
    ? '5px 5px 10px rgba(0, 0, 0, 0.5), -5px -5px 10px rgba(30, 30, 40, 0.3), 0 0 15px rgba(0, 255, 242, 0.2)'
    : '5px 5px 10px rgba(200, 200, 220, 0.3), -5px -5px 10px rgba(255, 255, 255, 0.8), 0 0 15px rgba(0, 180, 170, 0.1)',
  transition: 'all 0.3s ease',
  '&::before': {
    content: '""',
    position: 'absolute',
    top: 0,
    left: '50%',
    width: '100%',
    height: '2px',
    background: theme.palette.mode === 'dark'
      ? 'linear-gradient(90deg, transparent, #00fff2, transparent)'
      : 'linear-gradient(90deg, transparent, #00b4aa, transparent)',
    transform: 'translateX(-50%)',
  },
  '&:hover': {
    transform: 'translateY(-5px)',
    boxShadow: theme.palette.mode === 'dark'
      ? '8px 8px 15px rgba(0, 0, 0, 0.6), -8px -8px 15px rgba(30, 30, 40, 0.4), 0 0 20px rgba(0, 255, 242, 0.3)'
      : '8px 8px 15px rgba(200, 200, 220, 0.4), -8px -8px 15px rgba(255, 255, 255, 0.9), 0 0 20px rgba(0, 180, 170, 0.2)',
  },
}));

const PlanTitle = styled(Typography)(({ theme }) => ({
  fontFamily: '"Rajdhani", "Poppins", sans-serif',
  fontSize: '2.2rem',
  fontWeight: '700',
  textAlign: 'center',
  letterSpacing: '0.05em',
  color: theme.palette.mode === 'dark' ? '#ffffff' : '#000000',
  marginBottom: theme.spacing(1),
}));

const PlanPrice = styled(Typography)(({ theme }) => ({
  fontFamily: '"Rajdhani", "Poppins", sans-serif',
  fontSize: '3rem',
  fontWeight: '700',
  textAlign: 'center',
  color: theme.palette.mode === 'dark' ? '#00fff2' : '#00b4aa',
  textShadow: theme.palette.mode === 'dark' 
    ? '0 0 10px rgba(0, 255, 242, 0.7)' 
    : '0 0 8px rgba(0, 180, 170, 0.3)',
  marginBottom: theme.spacing(4),
}));

const RecurringPeriod = styled(Typography)(({ theme }) => ({
  fontFamily: '"Rajdhani", "Poppins", sans-serif',
  fontSize: '1.2rem',
  color: theme.palette.mode === 'dark' ? 'rgba(255, 255, 255, 0.7)' : 'rgba(0, 0, 0, 0.7)',
  textAlign: 'center',
  marginTop: theme.spacing(-3),
  marginBottom: theme.spacing(3),
}));

const CyberButton = styled(Button)(({ theme, disabled }) => ({
  background: disabled
    ? theme.palette.mode === 'dark'
      ? 'linear-gradient(145deg, rgba(60, 60, 70, 0.5), rgba(40, 40, 50, 0.5))'
      : 'linear-gradient(145deg, rgba(220, 220, 230, 0.8), rgba(200, 200, 210, 0.8))'
    : theme.palette.mode === 'dark'
      ? 'linear-gradient(145deg, rgba(0, 255, 242, 0.3), rgba(0, 200, 190, 0.2))'
      : 'linear-gradient(145deg, rgba(0, 210, 200, 0.6), rgba(0, 180, 170, 0.4))',
  color: disabled
    ? theme.palette.mode === 'dark' ? 'rgba(255, 255, 255, 0.5)' : 'rgba(0, 0, 0, 0.5)'
    : theme.palette.mode === 'dark' ? '#ffffff' : '#000000',
  textShadow: disabled 
    ? 'none' 
    : theme.palette.mode === 'dark' ? '0 0 5px rgba(0, 255, 242, 0.5)' : 'none',
  fontFamily: '"Rajdhani", "Poppins", sans-serif',
  fontSize: '1.3rem',
  fontWeight: '600',
  padding: theme.spacing(1.2, 2),
  borderRadius: '12px',
  textTransform: 'none',
  letterSpacing: '0.05em',
  transition: 'all 0.3s ease',
  boxShadow: disabled
    ? 'none'
    : theme.palette.mode === 'dark'
      ? 'inset 1px 1px 2px rgba(0, 0, 0, 0.2), inset -1px -1px 2px rgba(255, 255, 255, 0.05)'
      : 'inset 1px 1px 3px rgba(0, 160, 150, 0.3), inset -1px -1px 3px rgba(255, 255, 255, 0.8)',
  '&:hover': {
    background: disabled
      ? theme.palette.mode === 'dark'
        ? 'linear-gradient(145deg, rgba(60, 60, 70, 0.5), rgba(40, 40, 50, 0.5))'
        : 'linear-gradient(145deg, rgba(220, 220, 230, 0.8), rgba(200, 200, 210, 0.8))'
      : theme.palette.mode === 'dark'
        ? 'linear-gradient(145deg, rgba(0, 255, 242, 0.4), rgba(0, 200, 190, 0.3))'
        : 'linear-gradient(145deg, rgba(0, 210, 200, 0.7), rgba(0, 180, 170, 0.5))',
    color: disabled
      ? theme.palette.mode === 'dark' ? 'rgba(255, 255, 255, 0.5)' : 'rgba(0, 0, 0, 0.5)'
      : theme.palette.mode === 'dark' ? '#ffffff' : '#000000',
    textShadow: disabled 
      ? 'none' 
      : theme.palette.mode === 'dark' ? '0 0 8px rgba(0, 255, 242, 0.7)' : 'none',
    transform: disabled ? 'none' : 'translateY(-2px)',
  },
}));

const StyledList = styled(List)(({ theme }) => ({
  padding: theme.spacing(1, 0, 3),
}));

const StyledListItem = styled(ListItem)(({ theme }) => ({
  padding: theme.spacing(0.5, 1),
}));

const FeatureText = styled(ListItemText)(({ theme }) => ({
  '& .MuiListItemText-primary': {
    fontFamily: '"Rajdhani", "Poppins", sans-serif',
    fontSize: '1.1rem',
    color: theme.palette.mode === 'dark' ? 'rgba(255, 255, 255, 0.9)' : 'rgba(0, 0, 0, 0.8)',
  },
}));

const StyledCheckIcon = styled(CheckIcon)(({ theme }) => ({
  color: theme.palette.mode === 'dark' ? '#00fff2' : '#00b4aa',
  filter: theme.palette.mode === 'dark' ? 'drop-shadow(0 0 2px rgba(0, 255, 242, 0.7))' : 'none',
}));

const CyberCardHeader = styled(CardHeader)(({ theme }) => ({
  padding: theme.spacing(3, 2, 1),
  '& .MuiCardHeader-content': {
    width: '100%',
  },
}));

const CyberCardContent = styled(CardContent)(({ theme }) => ({
  padding: theme.spacing(2, 3, 3),
}));

const CyberDialog = styled(Dialog)(({ theme }) => ({
  '& .MuiPaper-root': {
    background: theme.palette.mode === 'dark'
      ? 'linear-gradient(145deg, rgba(20, 20, 30, 0.95), rgba(10, 10, 15, 0.98))'
      : 'linear-gradient(145deg, rgba(255, 255, 255, 0.95), rgba(240, 240, 250, 0.98))',
    borderRadius: '16px',
    border: theme.palette.mode === 'dark'
      ? '1px solid rgba(0, 255, 242, 0.2)'
      : '1px solid rgba(0, 180, 170, 0.2)',
    boxShadow: theme.palette.mode === 'dark'
      ? '0 0 30px rgba(0, 0, 0, 0.8), 0 0 15px rgba(0, 255, 242, 0.2)'
      : '0 0 30px rgba(0, 0, 0, 0.2), 0 0 15px rgba(0, 180, 170, 0.1)',
    overflow: 'hidden',
    '&::before': {
      content: '""',
      position: 'absolute',
      top: 0,
      left: '50%',
      width: '80%',
      height: '2px',
      background: theme.palette.mode === 'dark'
        ? 'linear-gradient(90deg, transparent, #00fff2, transparent)'
        : 'linear-gradient(90deg, transparent, #00b4aa, transparent)',
      transform: 'translateX(-50%)',
    },
  },
}));

const DialogTitleStyled = styled(DialogTitle)(({ theme }) => ({
  fontFamily: '"Rajdhani", "Poppins", sans-serif',
  fontSize: '1.8rem',
  fontWeight: '600',
  color: theme.palette.mode === 'dark' ? '#ffffff' : '#000000',
  padding: theme.spacing(3, 3, 2),
}));

const DialogContentStyled = styled(DialogContent)(({ theme }) => ({
  fontFamily: '"Rajdhani", "Poppins", sans-serif',
  fontSize: '1.2rem',
  color: theme.palette.mode === 'dark' ? 'rgba(255, 255, 255, 0.8)' : 'rgba(0, 0, 0, 0.8)',
  padding: theme.spacing(1, 3, 2),
}));

const DialogActionsStyled = styled(DialogActions)(({ theme }) => ({
  padding: theme.spacing(2, 3, 3),
}));

const PlanCard = ({
  plan,
  monthly,
  setSelectedPlan,
  currentSubscription,
  cardsData,
}) => {
  const { t } = useTranslation();
  const [loading, setLoading] = useState(false);
  const [confirmDialog, setConfirmDialog] = useState(false);
  const queryClient = useQueryClient();
  const stripe = useStripe();
  //const theme = useTheme();

  const mutation = useMutation(Subscribe);
  const customerPortalSessionMutate = useMutation(CreateCustomerPortalSession);

  const redirectToCustomerPortalSession = async () => {
    const response = await customerPortalSessionMutate.mutateAsync();
    window.location.href = response.data.redirect_url;
  };

  const handleSuccess = (message = t("planCard.planUpdated")) => {
    queryClient.invalidateQueries(["Me"]);
    ConfirmAlert.success(message);
    setTimeout(() => {
      window.location.href = "/dashboard";
    }, 3000);
  };

  const onUpdatePlanSubmit = async (planId) => {
    if (!stripe) {
      return;
    }

    try {
      setLoading(true);
      const response = await mutation.mutateAsync({ 
        planId,
        planType: plan.planType // Add planType from plan prop
      });

      if (response.data.latest_invoice.payment_intent?.client_secret) {
        const { error } = await stripe.confirmCardPayment(
          response.data.latest_invoice.payment_intent.client_secret,
          {
            setup_future_usage: "off_session",
          }
        );

        if (error) {
          throw new Error(error.message);
        }
        handleSuccess();
      } else if (response.data.latest_invoice.paid) {
        handleSuccess();
      } else {
        handleSuccess(response.data.message);
      }
    } catch (error) {
      console.log("error ---- ", error);
      ConfirmAlert.error(t("stripeForm.paymentFailed"));
      setTimeout(() => {
        window.location.href = "/dashboard";
      }, 3000);
      setLoading(false);
    }
  };

  const handlePlanUpdate = (planId) => {
    if (ENABLE_CUSTOMER_PORTAL) {
      return redirectToCustomerPortalSession();
    }
    setConfirmDialog(true);
  };

  const renderButton = () => {
    if (!currentSubscription) {
      return (
        <CyberButton
          fullWidth
          onClick={() => setSelectedPlan(plan.id)}
        >
          {t("planCard.selectPlan")}
        </CyberButton>
      );
    }

    const isCurrentPlan = currentSubscription.plan.id === plan.id;
    const isActive = currentSubscription.status === "active";
    const isPastDue = currentSubscription.status === "past_due";
    const isIncomplete = currentSubscription.status === "incomplete";

    if (isCurrentPlan && isActive) {
      return (
        <CyberButton fullWidth disabled>
          {t("planCard.currentPlan")}
        </CyberButton>
      );
    }

    if (isCurrentPlan && isPastDue) {
      return (
        <CyberButton fullWidth>
          {t("planCard.toPay")}
        </CyberButton>
      );
    }

    if (isActive || isIncomplete) {
      return (
        <CyberButton
          fullWidth
          onClick={() => cardsData.length === 0 
            ? setSelectedPlan(plan.id)
            : handlePlanUpdate(plan.id)
          }
        >
          {t("planCard.changePlan")}
        </CyberButton>
      );
    }
  };

  // Format the price for display with larger currency symbol
  const formattedPrice = formatMoney("it", plan.currency, plan.price);
  
  return (
    <>
      <CyberCard>
        {loading ? (
          <Loader />
        ) : (
          <>
            <CyberCardHeader
              title={
                <>
                  <PlanTitle>
                    {plan.title}
                  </PlanTitle>
                  <PlanPrice>
                    {formattedPrice}
                  </PlanPrice>
                  <RecurringPeriod>
                    {monthly ? t("planCard.month") : t("planCard.year")}
                  </RecurringPeriod>
                </>
              }
            />
            <CyberCardContent>
              <StyledList>
                {plan.features.map((feature, i) => (
                  <StyledListItem key={`feature-${i}`}>
                    <ListItemIcon>
                      <StyledCheckIcon />
                    </ListItemIcon>
                    <FeatureText primary={t(feature)} />
                  </StyledListItem>
                ))}
              </StyledList>
              {renderButton()}
            </CyberCardContent>
          </>
        )}
      </CyberCard>

      <CyberDialog
        open={confirmDialog}
        onClose={() => setConfirmDialog(false)}
      >
        <DialogTitleStyled>
          {t("planCard.updateSubscription")}
        </DialogTitleStyled>
        <DialogContentStyled>
          {t("planCard.areYou Sure")}
        </DialogContentStyled>
        <DialogActionsStyled>
          <CyberButton onClick={() => setConfirmDialog(false)}>
            {t("planCard.no")}
          </CyberButton>
          <CyberButton
            onClick={() => {
              setConfirmDialog(false);
              onUpdatePlanSubmit(plan.id);
            }}
          >
            {t("planCard.yes")}
          </CyberButton>
        </DialogActionsStyled>
      </CyberDialog>
    </>
  );
};

export default PlanCard;